package com.jiamao.goplay.ui.user.vm;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.alibaba.fastjson.JSONObject;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResUserInfoDetail;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.SearchFragment;
import com.jiamao.goplay.ui.settings.SettingsFragment;
import com.jiamao.goplay.ui.user.AnonymousReportFragment;
import com.jiamao.goplay.ui.user.OthersUserInfoFragment;
import com.jiamao.goplay.ui.user.UserInvitationFragment;
import com.jiamao.goplay.ui.user.UserPairFragment;
import com.jiamao.goplay.ui.user.UserWantGoToFragment;
import com.jiamao.goplay.ui.user.UserEditUserInfoFragment;
import com.jiamao.goplay.util.GsonUtil;
import com.jiamao.goplay.util.StringUtils;
import com.tamsiree.rxkit.view.RxToast;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;

public class MeVM extends BaseViewModel<DataRepository> {

    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>("");
    public ObservableField<String> imgUrl = new ObservableField<>("");
    public ObservableField<String> phoneNum = new ObservableField<>("0/6");
    public ObservableField<String> gotoNum = new ObservableField<>("0");
    public ObservableField<String> invNum = new ObservableField<>("0");
    public ObservableField<String> paifNum = new ObservableField<>("0");

    public ObservableField<String> gotoNumDec = new ObservableField<>("我想去的（0）");
    public ObservableField<String> phoneNumDec = new ObservableField<>("0张");
    public ObservableField<String> age = new ObservableField<>("");
    public ObservableField<String> sz = new ObservableField<>("");
    public ObservableField<String> sg = new ObservableField<>("");
    public ObservableField<String> tz = new ObservableField<>("");
    public ObservableField<String> hy = new ObservableField<>("");
    public ObservableField<String> zw = new ObservableField<>("");
    public ObservableField<String> dx = new ObservableField<>("");
    public ObservableField<String> ah = new ObservableField<>("");
    public ObservableField<String> gs = new ObservableField<>("");
    public ObservableField<String> des = new ObservableField<>("添加关于我，可以获得更多的邀请和回复...");
    public ObservableField<String> id = new ObservableField<>("0");

    public ObservableField<Integer> isVip = new ObservableField<>();

    public ObservableField<Integer> isShming = new ObservableField<>();
    public ObservableField<Integer> isRenXiang = new ObservableField<>();

//封装一个界面发生改变的观察者
public UIChangeObservable uc = new UIChangeObservable();

public class UIChangeObservable {
    //密码开关观察者
    public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Integer> pShimingEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Integer> pRenxiangEvent = new SingleLiveEvent<>();
}

    public MeVM(@NonNull Application application, DataRepository repository) {
        super(application, repository);
        //从本地取得数据绑定到View层

//        for (int i=0;i<3;i++){
//            MultiItemViewModel item = new UserWantGotoItemVM(this);
//            item.multiItemType("image");
//            observableList.add(item) ;
//
//        }
        MultiItemViewModel item = new MeGoToAddrItemVM(this);
        //条目类型为右布局
        item.multiItemType("add");
        observableList.add(item);


//
//        for (int i=0;i<5;i++){
//            MultiItemViewModel item2 = new MePhotoItemVM(this);
//            item2.multiItemType("image");
//            observableListImage.add(item2) ;
//
//        }
        MultiItemViewModel item2 = new MePhotoAddrItemVM(this);
        //条目类型为右布局
        item2.multiItemType("add");
           observableListImage.add(item2);

    }




    //登录按钮的点击事件
    public BindingCommand settingsCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(SettingsFragment.class.getCanonicalName());
        }
    });

    //编辑按钮点击事件
    public BindingCommand editUserInfoCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(UserEditUserInfoFragment.class.getCanonicalName());
        }
    });

    //编辑按钮点击事件
    public BindingCommand otherInfoCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(OthersUserInfoFragment.class.getCanonicalName());
        }
    });
    //登录按钮的点击事件
    public BindingCommand editCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            startContainerActivity(UserEditUserInfoFragment.class.getCanonicalName());
        }
    });

    //登录按钮的点击事件
    public BindingCommand editDesCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (des.get().equals("添加关于我，可以获得更多的邀请和回复...")){
                startContainerActivity(UserEditUserInfoFragment.class.getCanonicalName());
            }

        }
    });

    //登录按钮的点击事件
    public BindingCommand photoComdd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            RxToast.showToastShort("敬请期待");
            //startContainerActivity(AnonymousReportFragment.class.getCanonicalName());
        }
    });

    //登录按钮的点击事件
    public BindingCommand shimingCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            RxToast.showToastShort("敬请期待");
        }
    });

    //登录按钮的点击事件
    public BindingCommand gotoAddrCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(SearchFragment.class.getCanonicalName());
        }
    });

    //邀请我的
    public BindingCommand  invitationCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(UserInvitationFragment.class.getCanonicalName());
        }
    });

    //邀请我的
    public BindingCommand  paifCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(UserPairFragment.class.getCanonicalName());
        }
    });

    //邀请我的
    public BindingCommand  wanttogoCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(UserWantGoToFragment.class.getCanonicalName());
        }
    });

    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();
            if ("image".equals(itemType)) {
                //设置头布局
                itemBinding.set(BR.viewModel, R.layout.me_home_user_goto_addr_item_layout);

            } else  {
                //设置右布局
                itemBinding.set(BR.viewModel, R.layout.me_home_user_goto_addr_item_add_layout);
            }
           // itemBinding.set(BR.viewModel, R.layout.msg_home_item_layout);

        }
    });



    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableListImage = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBindingImage = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();
            if ("image".equals(itemType)) {
                //设置头布局
                itemBinding.set(BR.viewModel, R.layout.me_home_user_photo_item_layout);

            } else  {
                //设置右布局
                itemBinding.set(BR.viewModel, R.layout.me_home_user_photo_item_add_layout);
            }
            // itemBinding.set(BR.viewModel, R.layout.msg_home_item_layout);

        }
    });


    public void updateUserInfo(ResUserInfoDetail info){
        if (info.getCertification() != null){
            isVip.set(info.getCertification().getIsVip() == 0? View.GONE:View.VISIBLE);
            isRenXiang.set(info.getCertification().getAvatarVerified() == 0? View.GONE:View.VISIBLE);
            isShming.set(info.getCertification().getRealNameVerified() == 0? View.GONE:View.VISIBLE);

            uc.pShimingEvent.setValue(info.getCertification().getRealNameVerified());
            uc.pRenxiangEvent.setValue(info.getCertification().getAvatarVerified());
        }
        if (info.getBaseInfo() != null){
            userName.set( info.getBaseInfo().getNickname());
            imgUrl.set( info.getBaseInfo().getAvatar());
            id.set(info.getBaseInfo().getId()+"");
        }


        if (info.getAvatarList() != null){
            phoneNum.set(info.getAvatarList().size()+"/6");
            phoneNumDec.set(info.getAvatarList().size()+"张");
            observableListImage.clear();

            ArrayList<String> imgList = new ArrayList<>();
             for (int i=0;i<info.getAvatarList().size();i++){
                 imgList.add(info.getAvatarList().get(i).getUrl());
            }
            for (int i=0;i<info.getAvatarList().size();i++){
                KLog.d("img:"+info.getAvatarList().get(i),imgList);
                MultiItemViewModel itemPhone= new MePhotoItemVM(this,info.getAvatarList().get(i),imgList,i);
                itemPhone.multiItemType("image");
                observableListImage.add(itemPhone) ;

            }
            if (info.getAvatarList().size()<6) {
                MultiItemViewModel item2 = new MePhotoAddrItemVM(this);
                //条目类型为右布局
                item2.multiItemType("add");
                observableListImage.add(item2);
            }

        }

        if (info.getPlaceWantGo() != null){
            gotoNumDec.set("我想去的（"+info.getPlaceWantGo().size()+"）");
            gotoNum.set(info.getPlaceWantGo().size()+"");
//            gotoNumDec.set("我想要的("+info.getPlaceWantGo().size()+")");


            observableList.clear();
            for (int i=0;i<info.getPlaceWantGo().size();i++){


                MultiItemViewModel item = new UserWantGotoItemVM(this,   info.getPlaceWantGo().get(i));
                item.multiItemType("image");
                observableList.add(0,item) ;

            }
            if (info.getPlaceWantGo().size()<9){
                MultiItemViewModel item = new MeGoToAddrItemVM(this);
                //条目类型为右布局
                item.multiItemType("add");
                observableList.add(item);
            }

        }

        if (info.getInviteInfo() != null){
            paifNum.set(StringUtils.formatBigNum(info.getInviteInfo().getMatchNum()));
            invNum.set(StringUtils.formatBigNum(info.getInviteInfo().getInviteMyNum())+"");


        }
        if (info.getUserInfo() != null){
            age.set(info.getUserInfo().getAge());
            sz.set(info.getUserInfo().getGalaxy());
            sg.set(info.getUserInfo().getHeight());
            tz.set(info.getUserInfo().getWeight());
            hy.set(info.getUserInfo().getIndustry());
            zw.set(info.getUserInfo().getPosition());
            dx.set(info.getUserInfo().getUniversity());
            ah.set(info.getUserInfo().getInterest());
            gs.set(info.getUserInfo().getCompany());
            if (!TextUtils.isEmpty(info.getUserInfo().getDescribe())){
                des.set(info.getUserInfo().getDescribe());
            }
        //    des.set(info.getUserInfo().getDescribe());
        }




    }

    public void getUserInfoDB(){
        KLog.d("getUserinfoBD");
        try {
            ResUserInfoDetail userInfoDetail =  JSONObject.parseObject(model.getmLocalDataSource().getUserInfo(),ResUserInfoDetail.class);
            if (userInfoDetail!=null){
                updateUserInfo(userInfoDetail);
            }
        }catch (Exception e){

            e.printStackTrace();
        }

    }

    public void getUserInfoDetail(){

        BaseSubscriber subscription = new BaseSubscriber<BaseRep<ResUserInfoDetail>>() {

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                uc.pSwitchEvent.setValue(true);
                e.printStackTrace();
                RxToast.showToastShort("网络出现故障");
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onNext(BaseRep<ResUserInfoDetail> baseRep) {
                super.onNext(baseRep);
                uc.pSwitchEvent.setValue(true);
                // dismissDialog();
                // dialog.dismiss();
                //保存账号密码
                if (baseRep.isOk()){

                    model.getmLocalDataSource().saveSex(baseRep.getData().getBaseInfo().getGender());
                    model.getmLocalDataSource().saveUserInfo(GsonUtil.toJson(baseRep.getData()));
                    updateUserInfo(baseRep.getData());
//                                uc.reBtnGetCode.setValue(false)

                }else {
                    RxToast.showToastShort(baseRep.getMsg());
//
                }
            }
        };

        model.getApi().getMyUserInfo()
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(subscription);



    }


    public void getInitUserLoad(){

        BaseSubscriber subscription = new BaseSubscriber<BaseRep<ResUserInfoDetail>>() {

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onNext(BaseRep<ResUserInfoDetail> baseRep) {
                super.onNext(baseRep);
              //  uc.pSwitchEvent.setValue(true);
                // dismissDialog();
                // dialog.dismiss();
                //保存账号密码
                if (baseRep.isOk()){

                    model.getmLocalDataSource().saveSex(baseRep.getData().getBaseInfo().getGender());
                    model.getmLocalDataSource().saveUserInfo(GsonUtil.toJson(baseRep.getData()));
                    updateUserInfo(baseRep.getData());
//                                uc.reBtnGetCode.setValue(false)

                }else {
                 //   RxToast.showToastShort(baseRep.getMsg());
//
                }
            }
        };

        model.getApi().getMyUserInfo()
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(subscription);



    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
